package com.vitas.coin.vm

import android.Manifest
import android.content.DialogInterface.OnDismissListener
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.viewModelScope
import com.snap.base.ktx.reduceFreeCount
import com.snap.base.util.BaseUtil
import com.snap.common.main.BaseVM
import com.snap.common.permission.PermissionUtil
import com.snap.dialog.commonDialog
import com.snap.util.Util
import com.snap.util.log.SLog
import com.snap.util.toast
import com.vitas.coin.R
import com.vitas.coin.callback.IDownloadListener
import com.vitas.coin.constant.AppConstant
import com.vitas.coin.data.bean.ChildrenVoiceBean
import com.vitas.coin.data.bean.DownloadedBean
import com.vitas.coin.data.event.DownloadEvent
import com.vitas.coin.db.DBListener
import com.vitas.coin.db.DownDao
import com.vitas.coin.manager.RingtoneHelper
import com.vitas.coin.ui.dialog.LoadingDialog
import com.vitas.coin.util.DownloadUtil
import com.vitas.coin.util.PermissionsUtils
import kotlinx.coroutines.launch
import java.io.File


open class BaseMusicVM : BaseVM() {

    var mDialog: LoadingDialog? = null

    lateinit var actionAct: () -> FragmentActivity

    /**
     * type 1下载 2 设置铃声
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun download(
        mChildrenVoiceBean: ChildrenVoiceBean,
        funType: Int,
        editAct: ((String?, String) -> Unit)? = null,
        listener: OnDismissListener? = null
    ) {
        if (funType == 2) {
            if (!Settings.System.canWrite(actionAct.invoke())) {
                showApplyPermissionPromptDialog(1, bean = mChildrenVoiceBean, listener = listener)
                return
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                showApplyPermissionPromptDialog(2, bean = mChildrenVoiceBean, listener = listener)
                return
            }
        }
        val requestList = ArrayList<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_AUDIO)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            requestList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if (!PermissionsUtils.checkPermissionsGroup(
                actionAct.invoke(),
                requestList.toTypedArray()
            )
        ) {
            mChildrenVoiceBean.voiceUrl?.let {
                mChildrenVoiceBean.name?.let { it1 ->
                    showApplyPermissionPromptDialog(
                        3, funType,
                        mChildrenVoiceBean,
                        editAct = editAct,
                        listener = listener
                    )
                }
            }
        } else {
            doDownload(funType, mChildrenVoiceBean, editAct, listener = listener)
        }
    }

    fun doDownload(
        funType: Int,
        mChildrenVoiceBean: ChildrenVoiceBean,
        editAct: ((String?, String) -> Unit)?,
        next: Runnable? = null,
        listener: OnDismissListener? = null
    ) {
        val tips = permissionTips(3)
        requestPermission(actionAct.invoke(), tips, actionNext = {
            if (next != null) {
                next.run()
                return@requestPermission
            }
            if (funType == 1 || funType == 3) {
                showLoadingDialog("下载中...", listener);
            } else {
                showLoadingDialog("设置中...", listener);
            }

            viewModelScope.launch {
                if (mChildrenVoiceBean.voiceUrl!!.startsWith("file://")) {
                    var f = File(Uri.parse(mChildrenVoiceBean.voiceUrl).path)
                    downloadEnd(f, funType, false, mChildrenVoiceBean, editAct)
                    return@launch
                }
                if (funType != 3) {
                    var tmp = DownDao().get(mChildrenVoiceBean.id)
                    if (tmp != null) {
                        downloadEnd(File(tmp.path), funType, false, mChildrenVoiceBean, editAct)
                        return@launch
                    }
                }
                DownloadUtil.get().download(
                    mChildrenVoiceBean.voiceUrl,
                    mChildrenVoiceBean.name,
                    object : IDownloadListener {
                        override fun onStart() {

                        }

                        override fun onProgress(progress: Int) {
                            loadingProgress(progress)
                        }

                        override fun onFailure(errorMes: String) {
                            SLog.e("onFailure$errorMes")
                            toast("下载失败, $errorMes")
                            dismissDialog()
                        }

                        override fun onDone(dstFile: File) {
                            downloadEnd(dstFile, funType, true, mChildrenVoiceBean, editAct)
                        }
                    })
            }
        })
    }

    fun showLoadingDialog(progressText: String, listener: OnDismissListener? = null) {
        if (mDialog == null) {
            mDialog = LoadingDialog(actionAct.invoke())
            mDialog?.setOnDismissListener {
                listener?.onDismiss(it)
                mDialog = null
            }
        }

        mDialog!!.setProgressText(progressText)

        if (!mDialog!!.isShowing) {
            mDialog!!.show()
        }
    }

    fun loadingProgress(progress: Int) {
        mDialog?.onProgress(progress)
    }

    fun dismissDialog() {
        if (mDialog == null) {
            return
        }

        if (!mDialog!!.isShowing) {
            return
        }

        mDialog!!.dismiss()
    }


    private fun jumpSetting() {
        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
        intent.setData(Uri.parse("package:" + actionAct.invoke().packageName))
        actionAct.invoke().startActivity(intent)
    }

    private fun jumpManager() {
        val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
        val uri = Uri.fromParts("package", actionAct.invoke().packageName, null)
        intent.setData(uri)
        actionAct.invoke().startActivity(intent)
    }

    private fun requestPermission(context: FragmentActivity, tips: String, actionNext: () -> Unit) {
        val requestList = ArrayList<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_AUDIO)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            requestList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        PermissionUtil.requestPermission(context, requestList, tips) {
            if (!it) {
                return@requestPermission
            }
            actionNext()
        }
//        val permissionMediator = PermissionX.init(context)
//        permissionMediator.permissions(requestList)
//            .onExplainRequestReason { scope, deniedList ->
//                val message = "需要您同意以下权限才能正常使用"
//                scope.showRequestReasonDialog(deniedList, message, "同意", "取消")
//            }
//            .request { allGranted, _, deniedList ->
//                if (!allGranted) {
//                    SLog.e("is not all granted deniedList:$deniedList")
//                    return@request
//                }
//                actionNext()
//            }
    }

    private fun permissionTips(permissionType: Int): String {
        val permissionTips = when (permissionType) {
            1 -> {
                "设置手机铃声需要允许修改系统设置，请您授予该权限";
            }

            2 -> {
                "设置和编辑手机铃声需要使用本地音乐文件管理权限，请您授予该权限";
            }

            else -> {
                "设置和编辑手机铃声需要使用存储权限，请您授予该权限";
            }
        }
        return permissionTips
    }

    fun showApplyPermissionPromptDialog(
        permissionType: Int,
        funType: Int = 0,
        bean: ChildrenVoiceBean,
        next: Runnable? = null,
        editAct: ((String?, String) -> Unit)? = null,
        listener: OnDismissListener? = null
    ) {
        if (TextUtils.isEmpty(bean.voiceUrl)) {
            return
        }
        commonDialog {
            setLayoutRes(R.layout.dialog_apply_permission_prompt) { view, dialog ->
                val tv_content: TextView = view.findViewById(R.id.tv_content)
                val permissionTips = permissionTips(permissionType)
                tv_content.text = permissionTips
                view.findViewById<View>(R.id.ll_confirm).setOnClickListener { view ->
                    if (permissionType == 1) {
                        jumpSetting()
                    } else if (permissionType == 2) {
                        jumpManager()
                    } else {
                        doDownload(funType, bean, editAct, next, listener)
                    }
                    dismiss()
                }
            }
            setCanceledOnTouchOutside(false)
            setCanceledOnBackPressed(false)
        }.show(actionAct.invoke())
    }

    fun downloadEnd(
        dstFile: File,
        funType: Int,
        isDownload: Boolean,
        bean: ChildrenVoiceBean?,
        editAct: ((String?, String) -> Unit)? = null
    ) {
        SLog.e(AppConstant.LOG_TAG, "onDone")
        dismissDialog()
        // 下载完要减去一次
        BaseUtil.reduceFreeCount()
        if (funType == 3) {
            if (isDownload) {
                toast("下载完成")
            }
            editAct?.invoke(bean?.name, dstFile.absolutePath)
            return
        }
        // 更新系统媒体库
        MediaScannerConnection.scanFile(
            Util.getApp(),
            arrayOf(dstFile.absolutePath),
            null
        ) { var1, uri ->
            if (isDownload && bean != null) {
                add2Downloaded(DownloadedBean(bean.id, dstFile.absolutePath))
            }
            if (funType == 1) {
                if (isDownload) {
                    toast("下载完成")
                }
                editAct?.invoke(bean?.name, dstFile.absolutePath)
            } else {
                RingtoneHelper.setRingtone(
                    actionAct.invoke(),
                    uri
                );
                toast("设置完成")
            }
        }
    }

    fun add2Downloaded(bean: DownloadedBean) {
        DownDao().insert(bean, object : DBListener {
            override fun onResult(bo: Boolean, msg: String?, result: Any?) {
                if (bo) {
                    BaseUtil.postEvent(DownloadEvent())
                }
            }
        })
    }
}